﻿package kliment.data {
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	/**
     * Dispatched when change.
     */
    [Event(name = 'change', type = 'flash.events.Event')]
	
	/**
	 * ...
	 * @author	Kliment
	 * @version	0.0.1
	 * 
	 * class name: kliment.data.ShopingCart
	 */
	public class ShopingCart extends EventDispatcher {
		private var _list:Array;
		
		public function ShopingCart() {
			_list = new Array();
		}
		
		public function add(value:ShopingCartItem):void {
			var item:ShopingCartItem = _list[_checkExist(value)];
			if (!item) {
				_list.push(value);
				value.host = this;
				value.addEventListener(Event.CHANGE, _itemChangeHandler);
			} else {
				item.count += value.count;
			}
			dispatchEvent(new Event(Event.CHANGE));
		}
		
		public function remove(index:Number):Void {
			var item:ShopingCartItem = _list.splice(index, 1);
			item.removeEventListener(Event.CHANGE, _itemChangeHandler);
			dispatchEvent(new Event(Event.CHANGE));
		}
		
		private function _itemHandler(target:Event):void {
			switch(target.type) {
				case Event.CHANGE: 
					dispatchEvent(new Event(Event.CHANGE));
				break;
			}
		}
		
		private function _checkExist(target:ShopingCartItem):Number {
			var i:Number = _list.length;
			while (i--) {
				var item:ShopingCartItem = _list[i];
				if (item.id == target.id) {
					return i;
				}
			}
			return -1;
		}
		
		public function get totalPrice():Number {
			var ruselt:Number = 0;
			var i:Number = _list.length;
			while (i--) {
				var item:ShopingCartItem = _list[i];
				ruselt += item.price * item.count;
			}
			return ruselt;
		}
		
		public function clear():void {
			_list = new Array();
			dispatchEvent(new Event(Event.CHANGE));
		}
		
		public function get length():Number { return _list.length }
		
		public function get dataPrivider():Array { return _list }
	}

}